package com.rtwo.redisdao;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Created by hasee on 2017/5/22.
 */
@Repository
public class RedisUtil{

    @Resource
    private RedisTemplate redisTemplate;

    public boolean set(String key,Object value){
        try{
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key,value);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String key,Object value,long expireTime){
        try{
            ValueOperations valueOperations = redisTemplate.opsForValue();
            valueOperations.set(key,value);
            redisTemplate.expire(key,expireTime,TimeUnit.SECONDS);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public Object get(String key){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        return valueOperations.get(key);
    }

    public boolean exsits(String key){
        return redisTemplate.hasKey(key);
    }

    public void remove(String key){
        if(exsits(key)){
            redisTemplate.delete(key);
        }
    }

    public void removePattern(String pattern){
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0)
            redisTemplate.delete(keys);
    }

    public void remove(String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }
}
